<template>
  <div class="register-view">
    <h1> 注册页面 </h1>
    <div class="input">
      <label>
	<span>用户名</span>
	<input type="text" v-model="username">
      </label>

      <label>
	<span>密码</span>
	<input type="password" v-model="password">
      </label>

      <label>
	<span>重复密码</span>
	<input type="password" v-model="repeatPassword">
      </label>

      <p class="error-message">{{errorMessage}}</p>
      <button @click="submitRegister" :disabled="errorMessage.length != 0">提交</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
 import { ref } from "@vue/reactivity";
 import {UserService} from '@/service'
 import { onMounted, watch } from "@vue/runtime-core";

 const username = ref('')
 const password = ref('')
 const repeatPassword = ref('')
 const errorMessage = ref('')
 
 async function submitRegister() {
   // UserService.register({username, password})
   let {message} = await UserService.register({
     name: username.value,
     password: password.value
   })
   
   errorMessage.value = message
 }

 watch(password, (value, old) => {
   if(value.length == 0) {
     errorMessage.value = 'please input password'
   } else if(value.length < 8) {
     errorMessage.value = 'the length of password must be more then 8'
   } else {
     errorMessage.value = ''
   }

 })

 watch(username, async (value, old) => {
   if(value.length == 0) {
     errorMessage.value = 'please input username'
   } else if(value.length < 5) {
     errorMessage.value = 'username must be more then 5'
   } else if(await UserService.hasUser(value)) {
     errorMessage.value = 'name must be unique'
   } else {
     errorMessage.value = ''
   }
 })

 watch(repeatPassword, (value, old) => {
   if(value.length == 0) {
     errorMessage.value = 'please repeat your password'
   } else if(value != password.value) {
     errorMessage.value = 'repeat password not match'
   } else {
     errorMessage.value = ''
   }
 })
</script>

<style lang="scss" scoped>
 div.register-view {
   margin-left: auto;
   margin-right: auto;
   max-width: 360px;
   background: #ffffff;
   padding: 45px;
   margin-top: 8%;
   font: 12px Georgia, "Times New Roman", Times, serif;
   text-shadow: 1px 1px 1px #FFF;
   box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);



   div.input {
     label {
       display: block;
       margin: 0px;

       span {
	 float: left;
	 width: 20%;
	 text-align: right;

       }

       input {
	 outline: 0;
	 background: #f2f2f2;
	 width: 70%;
	 border: 0;
	 margin: 0 0 15px;
	 padding: 15px;
	 box-sizing: border-box;
	 font-size: 14px;
       }
     }

     button {
       text-transform: uppercase;
       outline: 0;
       background: #4caf50;
       width: 30%;
       border: 0;
       padding: 15px;
       color: #ffffff;
       font-size: 14px;
       transition: all 0.3 ease;
       cursor: pointer;

       &:hover, &:active, &:focus {
	 background: #43a047;
       }
     }
   }
 }
</style>